//index.js
//获取应用实例
const app = getApp()
let canvas = require('../../common/js/canvas.js');
let Axios = require('../../common/js/ajax.js');
let WxValidate = require('../../common/js/WxValidate.js'); //表单验证
let Mtils = require('../../common/js/Mtils.min.js');
Mtils = Mtils.Mtils
Page({
	data: {
		openid: '',
		nickName: '',
		avatarUrl: '',
		curentNav: 2, //当前导航
		name: '',
		phone: '',
		provinceName: '',
		cityName: '',
		countyName: '',
		place: '',
		good: {},
		height: 866,
		top: 50,
		imgHeight: 0,
		hcImg: '',
		shareTk: false,
		canvasTk: false,
		followTk: false,
		goods_id: 0,
		tips: false
	},
	//事件处理函数
	onLoad: function(e) {
		var _this = this;
		this.setData({
			goods_id: e.goods_id
		})
		this.initValidate()
		this.load = this.selectComponent("#loading");
		if (app.globalData.nickName && app.globalData.avatarUrl) {
			this.setData({
				nickName: app.globalData.nickName,
				avatarUrl: app.globalData.avatarUrl
			})
		}
		this.uid = app.globalData.uid || ''
		this.Md5 = Mtils.security.hex_md5(this.uid) + app.globalData.secret;
		this.Md5 = Mtils.security.hex_md5(this.Md5);
		this.timesp = Mtils.now()
		Axios.get(app.globalData.baseUrl + 'App/Store/Order/order_goods_info', { //关键字
			goods_id: this.data.goods_id,
			uid: _this.uid,
			time: _this.timesp,
			sign: _this.Md5
		}, (res) => {
			console.log(res)
			if (res.status == 1) {
				var data = res.info
				_this.setData({
					good: data
				})
				if (e.address) {
					_this.setData({
						'good.address_info': e
					})
				}
				_this.load.loadIng()
			}
		})

	},
	onReady: function() {
		wx.setNavigationBarTitle({
			title: '下订单'
		})
	},
	preventTouchMove: function() {

	},
	bubbling: function() {

	},
	readFromWx: function() { //微信获取地址
		let _this = this;	
		if (wx.chooseAddress) {
			wx.chooseAddress({
				success: function(res) {	
					console.log(res)
					Axios.post(app.globalData.baseUrl + 'App/User/UserInfo/add_weixin_address', { //关键字
						uid: _this.uid,
						time: _this.timesp,
						sign: _this.Md5,
						full_name:res.userName,
						mobile:res.telNumber,
						address:res.detailInfo,
						province:res.provinceName,
						city:res.cityName,
						area:res.countyName
						
					}, (res) => {
						console.log(res)
						if (res.status == 1) {
							var data = res.info
							var address = {
								full_name: res.userName,
								mobile: res.telNumber,
								address: res.provinceName + res.cityName + res.countyName + res.detailInfo
							}
								_this.setData({
								'good.address_info': address,
								['good.address_info.id']:'0'
							})
							
							
						}
					})
				
				},
				fail: function(err) {
					console.log(JSON.stringify(err))
				}
			})
		}
	},
	handleAddTap: function() {
		var _this = this;
		var num = _this.data.good['num'];
		num = parseInt(num)
		if (num >= this.data.good.stock) {
			wx.showModal({
				content: '库存不够',
				showCancel: false,
			})
			return false
		}
		num += 1;
		_this.setData({
			'good.num': num
		})
	},
	handleReduceTap: function() {
		var _this = this;
		var num = _this.data.good['num'];
		num = parseInt(num)
		if (num > 1) {
			num -= 1;
			_this.setData({
				'good.num': num
			})
		}
	},
	handleFollowTap: function(e) { //关注
		var _this = this;
		var id = _this.data.good.store_info.id
		var follow = _this.data.good.store_info.is_follow
		if (follow == 1) {
			_this.setData({
				followTk: true,
			})
		} else {
			Axios.post(app.globalData.baseUrl + 'App/Store/Store/store_follow', {
				store_id: id,
				uid: this.uid,
				sign: this.Md5,
				time: this.timesp
			}, (res) => {
				console.log(res)
				if (res.status == 1) {
					_this.setData({
						['good.store_info.is_follow']: 1
					})

				}
			})
		}
	},
	handleCancelFoTap: function(e) { //取消关注
		var _this = this;
		var id = _this.data.good.store_info.id
		var follow = _this.data.good.store_info.is_follow
		if (follow == 1) {
			Axios.post(app.globalData.baseUrl + 'App/Store/Store/store_follow', {
				store_id: id,
				uid: this.uid,
				sign: this.Md5,
				time: this.timesp
			}, (res) => {
				console.log(res)
				if (res.status == 1) {
					_this.setData({
						['good.store_info.is_follow']: 0,
						followTk: false
					})

				}
			})
		}

	},
	handleShareTap: function() {
		var _this = this;
		_this.setData({
			shareTk: !_this.data.shareTk
		})
	},
	handleCloseTap: function() {
		this.setData({
			followTk: false, //取消关注		
			canvasTk: false, //合成图片		
			shareTk: false,
			height: 0,
			tips: false
		})
	},
	handleCanvasTap: function(e) { //合成图片				
		var id = e.currentTarget.dataset.id;
		//console.log(e.detail.x)
		var HEIGHT = 670;
		var _this = this;
		var picinit = 0;
		var logoinit = 0;
		var textH = canvas.heightComputed(this.data.good.share_content, 510, 28, 37)
		picinit = textH
		textH += canvas.heightComputed(this.data.good.title, 560, 28, 37)
		logoinit = textH
		console.log(_this.data.nickName)
		var fontWith = canvas.widthComputed(_this.data.nickName, 48)
		console.log(fontWith)
		this.setData({
			height: (textH + HEIGHT),
			imgHeight: (textH + HEIGHT),
			//top: e.detail.y
		})
		wx.showLoading({
			title: '绘图中···',
		})
		var avatarUrl = '';
		var temp_picture = '';
		var wxEwm = '';//二维码
		Axios.post(app.globalData.baseUrl + 'App/PublicCommon/Share/share_img', {
			object_id: id,
			type: 2
		}, (res) => {
			console.log(res)
			if (res.status == 1) {
				var data = res.info
				wx.downloadFile({
					url: app.globalData.baseUrl + data,
					success: function(res) {
						wxEwm = res.tempFilePath
						wx.downloadFile({
							url: _this.data.avatarUrl,
							success: function(res) {
								avatarUrl = res.tempFilePath
								if ( _this.data.good.goods_icon != '') {
									wx.downloadFile({
										url: app.globalData.baseUrl +  _this.data.good.goods_icon,
										success: function(res) {
											temp_picture = res.tempFilePath
											console.log(333)
											draws()
										},
										fail: function(fres) {
											wx.hideLoading();
										}
									})
								} else {
									draws()
								}
							},
							fail: function(fres) {
								wx.hideLoading();
							}
						})
					},
					fail: function(fres) {
						wx.hideLoading();
					}
				})
			} else {
				wx.hideLoading();
				_this.showModal(res)
			}
		})

		function draws() {
			app.ctx.setFillStyle('white')
			app.ctx.fillRect(0, 0, 650, (textH + HEIGHT) * .552)
			console.log(_this.data.avatarUrl)
			var avatar = {
				src: avatarUrl,
				x: 32,
				y: 53,
				width: 88,
				height: 88
			}
			canvas.drawAvatar(avatar)
			var proImg = {
				src: temp_picture,
				x: 178,
				y: 118 + picinit,
				width: 285,
				height: 285
			}
			canvas.drawImg(proImg)
			var canvasLogo = {
				src: '/img/canvasLogo.png',
				x: 43,
				y: 498 + logoinit,
				width: 333,
				height: 39
			}
			canvas.drawImg(canvasLogo)		
			var author = {
				x: 139,
				y: 70,
				color: '#006e88',
				size: 28,
				align: 'left',
				baseline: 'middle',
				text: _this.data.nickName,
				bold: true
			}
			canvas.drawText(author)
			var sign = {
				x: 158 + fontWith,
				y: 70,
				color: '#f08415',
				size: 28,
				align: 'left',
				baseline: 'middle',
				text: '推荐',
				bold: true
			}
			canvas.drawText(sign)
			var adverter = {
				x: 139,
				y: 118,
				width: 510,
				height: 34,
				line: 2,
				color: '#3f4446',
				size: 28,
				align: 'left',
				baseline: 'middle',
				bold: false,
				text: _this.data.good.share_content
			}
			canvas.textWrap(adverter)
			var desc = {
				x: 40,
				y: 455 + picinit,
				width: 560,
				height: 34,
				line: 2,
				color: '#3f4446',
				size: 28,
				align: 'left',
				baseline: 'middle',
				bold: false,
				text: _this.data.good.title
			}
			canvas.textWrap(desc)
			var wxLogo = {
				src:wxEwm,
				x: 468,
				y: 455 + logoinit,
				width: 138,
				height: 166
			}
			canvas.drawImg(wxLogo)
			var avatar2 = {
				src: avatarUrl,
				x: 506,
				y: 490 + logoinit,
				width: 68,
				height: 68
			}
			canvas.drawAvatar(avatar2)
			app.ctx.draw()
			setTimeout(function() {
				wx.canvasToTempFilePath({
					x: 0,
					y: 0,
					canvasId: 'firstCanvas',
					success: function(res) {
						wx.hideLoading();
						// 设置画布高度						
						_this.setData({
							hcImg: res.tempFilePath,
							canvasTk: true, //合成图片
							//tk: true,
							height: 0
						})
					}
				});
			}, 1000)
		}
	},
	handleSaveTap: function() { //保存到相册
		console.log('保存到相册')
		wx.getImageInfo({
			src: this.data.hcImg, //
			success: function(res) {
				wx.saveImageToPhotosAlbum({
					filePath: res.path,
					success: function(dres) {
						wx.showToast({
							title: '已保存到相册'
						})
					}
				})
			}
		})
	},
	onShareAppMessage: function(e) {
		var id = e.target.dataset.id
		let _this = this;
		this.setData({
			shareTk: false,
		})
		return {
			title: _this.data.good.desc, // 转发后 所显示的title
			path: '/pages/goodDetail/goodDetail?' + _this.data.good.id, // 相对的路径
			success: function(res) { // 成功后要做的事情
				console.log(res.shareTickets[0])
				// console.log
				wx.getShareInfo({
					shareTicket: res.shareTickets[0],
					success: function(res) {

					},
					fail: function(res) {
						console.log(res)
					},
					complete: function(res) {
						console.log(res)
					}
				})
			},
			fail: function(res) {
				// 分享失败
				console.log(res)
			}
		}
	},
	submit: function(e) {
		console.log(e.detail)
		var params = e.detail.value
		if (!this.WxValidate.checkForm(params)) {
			const error = this.WxValidate.errorList[0]
			this.showModal(error)
			return false
		}
		this.submitInfo(params);
	},
	submitInfo: function(e) {
		var _this = this
		var CONST = {
			uid: this.uid,
			time: this.timesp,
			sign: this.Md5
		}
		var obj = Object.assign(e, CONST);
		Axios.get(app.globalData.baseUrl + 'App/Store/Order/create_order',
			obj, (res) => {
				console.log(res)
				if (res.status == 1) {
					wx.navigateTo({
						url: '/pages/order/success/success'
					})
				} else {
					_this.showModal(res)
				}
			})
	},
	showModal: function(error) {
		wx.showModal({
			content: error.msg,
			showCancel: false,
		})
	},
	initValidate: function() {
		/** 4-2(配置规则)*/
		const rules = {
			goods_id: {
				required: true,
			},
			goods_num: {
				required: true,
			},
			address_id: {
				required: true,
			}
		}
		// 验证字段的提示信息，若不传则调用默认的信息
		const messages = {
			name: {
				goods_id: '请选择商品',
			},
			goods_num: {
				required: '请选择商品数量',
			},
			address_id: {
				required: '请选择快递地址',
			}
		}
		// 创建实例对象
		this.WxValidate = new WxValidate.WxValidate(rules, messages)
		/**
		 * 也可以自定义验证规则
		 */
		// 		this.WxValidate.addMethod('assistance', (value, param) => {
		// 			return this.WxValidate.optional(value) || (value.length >= 1 && value.length <= 2)
		// 		}, '请勾选 《顺风男服务协议》')
	}
})
